package com.alcohol.auth.server.support.core;

import com.alcohol.auth.server.config.AuthServerSecurityConfig;
import com.alcohol.auth.server.constant.ScopeDesc;
import com.alcohol.auth.server.entity.SysOAuthClient;
import com.alcohol.auth.server.service.SysOAuthClientService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.security.Principal;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

/**
 * @author LiXinYu
 * @date 2025/11/13
 */
@Controller
public class AuthServerCoreEndpoint {

    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private SysOAuthClientService sysOAuthClientService;

    @GetMapping(AuthServerSecurityConfig.LOGIN_PAGE)
//    public String login(Model model, @RequestParam(OAuth2ParameterNames.CLIENT_ID) String clientId,
//                        @RequestParam(OAuth2ParameterNames.SCOPE) String scopes) {
    public String login() {
//        SysOAuthClient sysOAuthClient = sysOAuthClientService.getSysOAuthClient(clientId);
//        if (Objects.isNull(sysOAuthClient)) {
//            throw new RuntimeException("客户端不存在");
//        }

//        model.addAttribute("clientName", sysOAuthClient.getClientName());
//        model.addAttribute("clientAvatar", sysOAuthClient.getClientAvatar());
//        model.addAttribute("scopes", ScopeDesc.getDesc(scopes));

        return "login1";
    }

    @PostMapping(AuthServerSecurityConfig.LOGIN_PAGE)
    @ResponseBody
    public Void login(HttpSession session, @RequestParam("username") String username, @RequestParam("password") String password) {
        UsernamePasswordAuthenticationToken authRequest = UsernamePasswordAuthenticationToken.unauthenticated(username, password);
        authenticationManager.authenticate(authRequest);
        System.out.println(session);

        return null;

//        @Override
//        public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
//			throws AuthenticationException {
//            if (this.postOnly && !request.getMethod().equals("POST")) {
//                throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
//            }
//            String username = obtainUsername(request);
//            username = (username != null) ? username.trim() : "";
//            String password = obtainPassword(request);
//            password = (password != null) ? password : "";
//            UsernamePasswordAuthenticationToken authRequest = UsernamePasswordAuthenticationToken.unauthenticated(username,
//                    password);
//            // Allow subclasses to set the "details" property
//            setDetails(request, authRequest);
//            return this.getAuthenticationManager().authenticate(authRequest);
//        }

//        return "login";
    }

    @GetMapping(AuthServerSecurityConfig.CUSTOM_CONSENT_PAGE)
    public String consent(Principal principal, Model model,
                          @RequestParam(OAuth2ParameterNames.CLIENT_ID) String clientId,
                          @RequestParam(OAuth2ParameterNames.SCOPE) String scope,
                          @RequestParam(OAuth2ParameterNames.STATE) String state,
                          @RequestParam(name = OAuth2ParameterNames.USER_CODE, required = false) String userCode) {
        Set<String> scopesToApprove = new HashSet<>();
        Set<String> previouslyApprovedScopes = new HashSet<>();
        RegisteredClient registeredClient = sysOAuthClientService.findByClientId(clientId);
        if (Objects.isNull(registeredClient)) {
            throw new RuntimeException("客户端不存在");
        }
        model.addAttribute("clientId", clientId);
        model.addAttribute("state", state);
        model.addAttribute("scopes", scopesToApprove);
        model.addAttribute("previouslyApprovedScopes", previouslyApprovedScopes);
        model.addAttribute("principalName", principal.getName());
        model.addAttribute("userCode", userCode);
        if (StringUtils.hasText(userCode)) {
            model.addAttribute("requestURI", "/oauth2/device_verification");
        } else {
            model.addAttribute("requestURI", "/oauth2/authorize");
        }

        return "consent";
    }
}
